//
//  UserAccount.swift
//  TakeTime
//
//  Created by bachelor on 16/11/1.
//  Copyright © 2016年 bachelor. All rights reserved.
//

import UIKit
import Alamofire

class UserAccount: NSObject, NSCoding {
    
    /// 用于调用access_token，接口获取授权后的access token
    var access_token: String
    /// access_token的生命周期，单位是秒数
    var expires_in: TimeInterval
    /// access_token具体过期时间
    var expiresDate: Date {
        
            return Date.init(timeIntervalSinceNow: expires_in)
    }
    /// 当前授权用户的UID
    var uid: String
    /// 友好显示名称
    var name: String?
    /// 用户头像地址（大图），180×180像素
    var avatar_large: String?
    
    init(dict: [String: AnyObject]) {
        access_token = dict["access_token"]! as! String
        expires_in = dict["expires_in"]! as! TimeInterval
        uid = dict["uid"]! as! String
    }
    
    
    
    ///  加载用户信息
    func loadUserInfo(finished: @escaping (_ account: UserAccount?, _ error: Error?) -> Void) {
        
        let params = ["access_token": self.access_token, "uid": self.uid]
        
        Alamofire.request("https://api.weibo.com/2/users/show.json", parameters: params).responseJSON { (response) in
            switch response.result {
            case .success:
                let JSON = response.result.value
                let dict = JSON as! [String: AnyObject]
                self.name = dict["name"] as? String
                self.avatar_large = dict["avatar_large"] as? String
                
                self.saveAccount()
                
                // 通知调用方，处理完成
                finished(self, nil)
                
            case .failure(let error):
                finished(nil, error)
            }
            
        }
        
    }
    
    
    override var description: String {
        let properties = ["access_token", "expires_in", "expiresDate", "uid", "name", "avatar_large"]
        return "\(dictionaryWithValues(forKeys: properties))"
    }
    
    // MARK: account的归档解档
    /// 归档路径
    static let accountPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] + "/account.plist"
    
    func saveAccount() {
        NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.accountPath)
        
    }
    class func loadAccount() -> UserAccount? {
        if let account = NSKeyedUnarchiver.unarchiveObject(withFile: UserAccount.accountPath) as? UserAccount {
            if account.expiresDate.compare(Date()) == ComparisonResult.orderedDescending {
                return account
            }
        }
        return nil
    }
    // 解档
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObject(forKey: "access_token") as! String
        expires_in = aDecoder.decodeDouble(forKey: "expires_in")
        
        uid = aDecoder.decodeObject(forKey: "uid") as! String
        name = aDecoder.decodeObject(forKey: "name") as? String
        avatar_large = aDecoder.decodeObject(forKey: "avatar_large") as? String
        
    }
    // 归档
    func encode(with aCoder: NSCoder) {
        aCoder.encode(access_token, forKey: "access_token")
        aCoder.encode(expires_in, forKey: "expires_in")
        aCoder.encode(uid, forKey: "uid")
        aCoder.encode(name, forKey: "name")
        aCoder.encode(avatar_large, forKey: "avatar_large")
    }
}
